//build:20240524
//To simplify the use of the cameraCalibration component, cameraCalibration is encapsulated within this worker. Users only need to subscribe to events from the eventcenter to listen to cameraCalibration.
import log from './dxLogger.js'
import cameraCalibration from './dxCameraCalibration.js'
import capturer from '../dxmodules/dxCapturer.js'
import center from './dxEventCenter.js'
import dxMap from './dxMap.js'
import * as os from "os";
const map = dxMap.get('default')
const options = map.get("__cameraCalibration__run_init")

function run() {
    cameraCalibration.init()
    log.info('cameraCalibration start......')
    let startTime = new Date().getTime()
    let cnt = 0
    while (true) {
        try {
            let imageRgb = capturer.readImage(options.capturerRgbId)
            let imageNir = capturer.readImage(options.capturerNirId)
            let res = cameraCalibration.calibrationFromImage(imageRgb, imageNir, cnt)
            if (res) {
                if (cnt >= 1) {
                    log.info("Calibration ends after two successful calibrations.")
                    cameraCalibration.getMap(imageRgb, imageNir, cnt, "/app/path.txt")
                    center.fire(cameraCalibration.RECEIVE_MSG, "success1")
                    capturer.destroyImage(imageRgb)
                    capturer.destroyImage(imageNir)
                    return
                }
                log.info("No." + (cnt + 1) + "Calibration successful.")
                center.fire(cameraCalibration.RECEIVE_MSG, "success0")
                cnt += 1
                log.info("Begin the first" + (cnt + 1) + "Sub-calibration")
            } else {
                log.error("No." + (cnt + 1) + "Calibration failed, retrying.")
            }
            capturer.destroyImage(imageRgb)
            capturer.destroyImage(imageNir)
            let endTime = new Date().getTime()
            if (endTime - startTime > options.timeout * 1000) {
                log.error('Calibration timed out, please re-perform the calibration.')
                center.fire(cameraCalibration.RECEIVE_MSG, "timeout")
                return
            }
        } catch (error) {
            log.error(error, error.stack)
        }
        os.sleep(10)
    }
}

try {
    run()
} catch (error) {
    log.error(error, error.stack)
}